package arkham.gui;

import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;

import javax.swing.*;

import arkham.util.ImageUtils;

public class ResizableImagePanel extends JPanel implements ComponentListener {

	private static final long serialVersionUID = 2882193216249708593L;
	private BufferedImage image;
	private BufferedImage baseImage;
	private boolean autoResize;

	/**
	 * Creates a resizable image panel. Autoresize is turned off, so the
	 * panel must be manually resized by calling the resizeImage function.
	 * @param img the image to use
	 */
	public ResizableImagePanel(BufferedImage img)
	{
		this(img, false);
	}

	/**
	 * Creates a resizable image panel, with the specified auto-resize
	 * settings. Auto-resize, if turned on, will cause the image to scale
	 * when the component is resized.
	 * @param img The image to use
	 * @param autoResize true to turn on autoresize
	 */
	public ResizableImagePanel(BufferedImage img, boolean autoResize)
	{
		super();
		this.image = img;
		this.baseImage = img;
		Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
		setPreferredSize(size);
		setSize(size);
		setOpaque(false);
		setLayout(null);
		setVisible(true);
		addComponentListener(this);
		this.autoResize = autoResize;
		if (!autoResize)
		{
			setMinimumSize(size);
		}
	}

	public void paintComponent(Graphics g)
	{
		if (autoResize && (getWidth() != image.getWidth() || getHeight() != image.getHeight()))
		{
			resizeImage(getWidth(), getHeight());
		}
		g.drawImage(image, 0, 0, null);
	}

	public void resizeImage(int width, int height)
	{
		image = ImageUtils.resizeImage(baseImage, width, height);
		Dimension size = new Dimension(width, height);
		setPreferredSize(size);
		setSize(size);
		if (!autoResize)
		{
			setMinimumSize(size);
		}
	}

	public void setImage(BufferedImage img)
	{
	    baseImage = img;
	    image = baseImage;
	    Dimension size = new Dimension(baseImage.getWidth(), baseImage.getHeight());
	    setPreferredSize(size);
	    setSize(size);
	    if (!autoResize)
        {
            setMinimumSize(size);
        }
	    repaint();
	}

	@Override
	public void componentHidden(ComponentEvent e) {

	}

	@Override
	public void componentMoved(ComponentEvent e) {

	}

	@Override
	public void componentResized(ComponentEvent e) {
		Component comp = e.getComponent();
		if (autoResize)
		{
			this.resizeImage(comp.getWidth(), comp.getHeight());
		}
	}

	@Override
	public void componentShown(ComponentEvent e) {

	}

}
